package com.yoda.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yoda.constant.MessageConstant;
import com.yoda.dto.UserDto;
import com.yoda.dto.YddUserPageDTO;
import com.yoda.entity.YddUser;
import com.yoda.mapper.YddUserMapper;
import com.yoda.result.PageResult;
import com.yoda.result.Result;

import com.yoda.context.BaseContext;
import com.yoda.dto.RegDto;
import com.yoda.entity.*;
import com.yoda.mapper.*;

import com.yoda.service.IYddUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.yoda.utils.JwtUtil;
import com.yoda.vo.*;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-05-15
 */
@Service
public class YddUserServiceImpl extends ServiceImpl<YddUserMapper, YddUser> implements IYddUserService {

    @Autowired
    private YddUserMapper yddUserMapper;
    @Autowired
    private YddCateMapper yddCateMapper;
    @Autowired
    private YddLinkMapper yddLinkMapper;

    @Autowired
    private YddTagMapper yddTagMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private YddAdvimgMapper yddAdvimgMapper;

    @Autowired
    private YddArticleMapper yddArticleMapper;

    @Autowired
    private YddUserDataMapper yddUserDataMapper;


    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public Result getById(Integer id) {
        YddUser yddUser = yddUserMapper.selectById(id);
        return Result.success(yddUser);
    }

    /**
     * 分页查询
     *
     * @param pageDTO
     * @return
     */
    @Override
    public Result yddPage(YddUserPageDTO pageDTO) {

//        1.非空判断
        if (pageDTO.getPage()==null){
           pageDTO.setPage(1);
        }
        if (pageDTO.getLimit()==null){
            pageDTO.setLimit(5);
        }
        //创建条件
        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(pageDTO.getSex()!=null,YddUser::getSex,pageDTO.getSex())
                .like(pageDTO.getMobile()!=null,YddUser::getMobile,pageDTO.getMobile())
                .like(pageDTO.getUsername()!=null,YddUser::getUsername,pageDTO.getUsername());

        //        2.创建IPage分页对象,设置分页参数
        IPage<YddUser> page = new Page<>(pageDTO.getPage(),pageDTO.getLimit());
        IPage<YddUser> iPage = yddUserMapper.selectPage(page, queryWrapper);

        PageResult pageResult = new PageResult();
        pageResult.setData(iPage.getRecords());
        pageResult.setCurrentPage(iPage.getCurrent());
        pageResult.setCount(iPage.getTotal());
        pageResult.setPageSize(iPage.getSize());
        pageResult.setTotalPages( iPage.getPages());
        return Result.success(pageResult);

    }
    /**
     * 新增员工
     *
     * @param yddUser
     * @return
     */
    @Override
    public Result add(YddUser yddUser) {
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(yddUser.getUsername()!=null,YddUser::getUsername,yddUser.getUsername());
        List<YddUser> list = list(wrapper);
        if (list!=null&&list.size()>0){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        yddUser.setDefaultData("1");
        save(yddUser);
        return Result.success();
    }

    /**
     * 修改
     *
     * @param userDTO
     * @return
     */
    @Override
    public Result update(UserDto userDTO) {
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
       wrapper.eq(userDTO.getName()!=null,YddUser::getUsername,userDTO.getName());
        List<YddUser> list = list(wrapper);
        if (list!=null&&list.size()>0){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        YddUser yddUser = new YddUser();
        BeanUtils.copyProperties(userDTO,yddUser);
        yddUserMapper.updateById(yddUser);

        return Result.success();
    }


    @Override
    public Result index() {
        IndexVo vo = new IndexVo();

        List<ChildrenVo> children = new ArrayList<>();

        List<YddCate> yddCateList = yddCateMapper.selectList(null);
        vo.setAllCate(yddCateList);
        vo.setAllLink(yddLinkMapper.selectList(null));
        vo.setAllTag(yddTagMapper.selectList(null));

        vo.setBanner(getydd("15"));
        LambdaQueryWrapper<YddAdvimg> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.in(YddAdvimg::getAdvimgpos,"12","13");
        List<YddAdvimg> yddAdvimgs = yddAdvimgMapper.selectList(lambdaQuery);
        vo.setShowBanner(yddAdvimgs);
        List<ConfigVo> configVos = new ArrayList<>();
        List<AllDataVo> allDataVoList = new ArrayList<>();
        List<ConfigListVo> configListVos = new ArrayList<>();

        List<ChildrenVo> childrenVoList = new ArrayList<>();
        childrenVoList.add(chidr("站点配置"));
        childrenVoList.add(chidr("底部信息"));
        childrenVoList.add(chidr("其他配置"));
        ConfigListVo configListVo = new ConfigListVo();
        configListVo.setChildren(childrenVoList);
        configListVo.setName("基础配置");
        configListVo.setKey("desc");
        configListVos.add(configListVo);

        configListVo = new ConfigListVo();
        childrenVoList = new ArrayList<>();
        childrenVoList.add(chidr("管理系统配置"));
        configListVo.setChildren(childrenVoList);
        configListVo.setName("系统配置");
        configListVo.setKey("system");
        configListVos.add(configListVo);

        configListVo = new ConfigListVo();
        childrenVoList = new ArrayList<>();
        childrenVoList.add(chidr("通知公告"));
        childrenVoList.add(chidr("前台图片"));
        configListVo.setChildren(childrenVoList);
        configListVo.setName("其他设置");
        configListVo.setKey("custom");
        configListVos.add(configListVo);


        List<SysConfig> sysConfigs = sysConfigMapper.selectList(null);
        BeanUtils.copyProperties(sysConfigs,allDataVoList);
        ConfigVo configVo = new ConfigVo();

        configVo.setAllData(allDataVoList);
        configVo.setList(configListVos);
        configVos.add(configVo);
        vo.setConfig(configVos);


        vo.setSideBanner(getydd("14"));
        return Result.success(vo);
    }

    /**
     * 热门置顶文章数据
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Result indexNew(String page, String pageSize) {
        IPage<YddArticle> iPage=new Page<>(Integer.valueOf(page),Integer.valueOf(pageSize));
        yddArticleMapper.selectPage(iPage,null);
        IndexNewVo vo = new IndexNewVo();
        vo.setDesc("我也不知道这是啥!数据库没有的数据都出来了");
        LocalDateTime dateTime = LocalDateTime.now();
        LocalDateTime plusDays = dateTime.plusDays(-1);
        LocalDateTime days = dateTime.plusDays(-7);
        //近1天的时间单位
        long time = Timestamp.valueOf(plusDays).getTime();
        //近七天的时间单位
        long time1 = Timestamp.valueOf(days).getTime();
        //获取近一天最新文章数据
        LambdaQueryWrapper<YddArticle> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.le(YddArticle::getCreateDate,time);
        Long numday = yddArticleMapper.selectCount(lambdaQuery);
        //获取近七天最新文章数据
        lambdaQuery=new LambdaQueryWrapper<>();
        lambdaQuery.le(YddArticle::getCreateDate,time1);
        Long numweek = yddArticleMapper.selectCount(lambdaQuery);

        vo.setNumDay(numday.intValue());
        vo.setNumWeek(numweek.intValue());

        DataPage dataPage = new DataPage();
        dataPage.setCount(iPage.getTotal());
        dataPage.setTotalPages(iPage.getPages());
        dataPage.setCurrentPage(iPage.getCurrent());
        dataPage.setPageSize(iPage.getSize());
        dataPage.setData(iPage.getRecords());

        vo.setList(dataPage);

        return Result.success(vo);


    }

    /**
     * 最新文章
     *
     * @return
     */
    @Override
    public Result indexHot() {
        IndexHotVo vo = new IndexHotVo();
        vo.setDesc("描述不知道写啥 抓不到包");
        List<HotVo> list = new ArrayList<>();
        List<YddCate> yddCates = yddCateMapper.selectList(null);
        yddCates.stream().forEach(yddCate -> {
            HotVo hotVo = new HotVo();
            Integer id = yddCate.getId();
            String catename = yddCate.getCatename();
            hotVo.setCateName(catename);
            LambdaQueryWrapper<YddArticle> query = Wrappers.lambdaQuery();
            query.eq(YddArticle::getCateid,id);
            List<YddArticle> yddArticles = yddArticleMapper.selectList(query);
            yddArticles.stream().forEach(yddArticle->{
                hotVo.setId(yddArticle.getId().longValue());
               hotVo.setTitle(yddArticle.getTitle());
               hotVo.setPic(yddArticle.getPic());
               hotVo.setLovennum(yddArticle.getClick()+"");
            });
            list.add(hotVo);
        });
        vo.setList(list);
        return Result.success(vo);
    }

    /**
     * 注册
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result reg(RegDto dto) {
        RegVo vo = new RegVo();
        YddUser user = new YddUser();
        BeanUtils.copyProperties(dto,user);
        user.setUsername(dto.getMobile());
        save(user);
        vo.setUserInfo(user);

        vo.setToken(JwtUtil.getToken(user.getId().longValue()));
        return Result.success(vo);
    }

    /**
     * 登入
     *
     * @param dto
     * @return
     */
    @Override
    public Result login(RegDto dto) {

        String mobile = dto.getMobile();
        String password = dto.getPassword();
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());

        QueryWrapper<YddUser> qw = new QueryWrapper();
        qw.lambda().eq(YddUser::getMobile,mobile);
        YddUser yddUser = getOne(qw);

        if (yddUser == null) {
            //账号不存在
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!pwd.equals(yddUser.getPassword())) {
            //密码错误
            return Result.error(MessageConstant.PASSWORD_ERROR);
        }

        String token = JwtUtil.getToken(Long.valueOf(yddUser.getId()));

        SysUserVo vo = SysUserVo.builder()
                .token(token)
                .build();

        return Result.success(vo);
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    @Override
    public Result show(Integer id) {
        //获取上一章信息
        ArtiVo artiVo = new ArtiVo();
        YddArticle yddArticle = yddArticleMapper.selectById(id - 1);
        if (yddArticle==null){
            artiVo.setId(null);
            artiVo.setTitle("没有更多文章数据");
        }else {
            artiVo.setId(yddArticle.getId());
            artiVo.setTitle(yddArticle.getTitle());
        }
        ShowVo vo = new ShowVo();
        vo.setPrev(artiVo);
        //获取下一章信息
        artiVo = new ArtiVo();
        yddArticle = yddArticleMapper.selectById(id +1);
        if (yddArticle==null){
            artiVo.setId(null);
            artiVo.setTitle("没有更多文章数据");
        }else {
            artiVo.setId(yddArticle.getId());
            artiVo.setTitle(yddArticle.getTitle());
        }
        vo.setNext(artiVo);
        YddArticle article = yddArticleMapper.selectById(id);
        YddArticleVo yddArticleVo = new YddArticleVo();
        BeanUtils.copyProperties(article,yddArticleVo);
        yddArticleVo.setIsLike("点赞");
        yddArticleVo.setIsCollect("收藏");
        vo.setInfo(yddArticleVo);
        List<RecommVo> recommend = new ArrayList<>();
        LambdaQueryWrapper<YddArticle> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(YddArticle::getIshot,"1");
        List<YddArticle> yddArticles = yddArticleMapper.selectList(lambdaQuery);
        yddArticles.stream().forEach(yddArticle1 -> {
            RecommVo recommVo = new RecommVo();
            recommVo.setId(yddArticle1.getId());
            recommVo.setCateid(yddArticle1.getCateid());
            recommVo.setPic(yddArticle1.getPic());
            recommVo.setTitle(yddArticle1.getTitle());
            recommend.add(recommVo);
        });
        vo.setRecommend(recommend);
        return Result.success(vo);
    }

    /**
     * 个人界面
     *
     * @return
     */
    @Override
    public Result getUserInfo() {
        Long id = BaseContext.getCurrentId();
        YddUser yddUser = getById(id);
        RegVo vo = new RegVo();
        vo.setUserInfo(yddUser);
        LambdaQueryWrapper<YddArticle> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(YddArticle::getUserId,id);
        Long aLong = yddArticleMapper.selectCount(lambdaQuery);
        if(aLong!=null){
            vo.setArticleNum(aLong.intValue());
        }
        LambdaQueryWrapper<YddUserData> query = Wrappers.lambdaQuery();
        query.eq(YddUserData::getUserId,id).eq(YddUserData::getType,2);
        List<YddUserData> userData = yddUserDataMapper.selectList(query);
        if(userData.size()!=0){
            vo.setZanNum(userData.size());
        }
        query = new LambdaQueryWrapper<>();
        query.eq(YddUserData::getUserId,id).eq(YddUserData::getType,1);
        List<YddUserData> yddUserData = yddUserDataMapper.selectList(query);
        if(yddUserData.size()!=0){
            vo.setCollectNum(yddUserData.size());
        }

        return Result.success(vo);
    }

    /**
     * 我的文章
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Result myArticle(String page, String pageSize) {
        LambdaQueryWrapper<YddArticle> query = Wrappers.lambdaQuery();
        query.eq(YddArticle::getUserId,BaseContext.getCurrentId());
        IPage<YddArticle> iPage=new Page<>(Integer.valueOf(page),Integer.valueOf(pageSize));
        IPage<YddArticle> articleIPage = yddArticleMapper.selectPage(iPage, query);
        DataPage dataPage = new DataPage();
        dataPage.setCount(articleIPage.getTotal());
        dataPage.setTotalPages(articleIPage.getPages());
        dataPage.setPageSize(articleIPage.getSize());
        dataPage.setCurrentPage(articleIPage.getCurrent());
        dataPage.setData(articleIPage.getRecords());

        return Result.success(dataPage);
    }

    /**
     * 我的收藏/点赞文章
     *
     * @param type
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Result userDataList(String type, String page, String pageSize) {
        UserDataVo vo = new UserDataVo();
        DataPage dataPage = new DataPage();
        LambdaQueryWrapper<YddUserData> query = Wrappers.lambdaQuery();
        query.eq(YddUserData::getUserId,BaseContext.getCurrentId()).eq(YddUserData::getType,type);
        List<YddUserData> yddUserDataList = yddUserDataMapper.selectList(query);
        List list = new ArrayList();
        yddUserDataList.stream().forEach(yddUserData -> {
            Integer articleId = yddUserData.getArticleId();
            list.add(articleId);
        });

        IPage<YddArticle> iPage=new Page<>(Integer.valueOf(page),Integer.valueOf(pageSize));
        IPage<YddArticle> articleIPage = yddArticleMapper.selectPage(iPage, new LambdaQueryWrapper<YddArticle>().in(YddArticle::getId,list));


        dataPage.setCount(articleIPage.getTotal());
        dataPage.setTotalPages(articleIPage.getPages());
        dataPage.setPageSize(articleIPage.getSize());
        dataPage.setCurrentPage(articleIPage.getCurrent());
        dataPage.setData(articleIPage.getRecords());

        vo.setList(dataPage);
        return Result.success(vo);
    }

    /**
     * 发布文章
     *
     * @param vo
     * @return
     */
    @Override
    public Result addArticle(AddArticleVo vo) {
        YddArticle yddArticle = new YddArticle();
        BeanUtils.copyProperties(vo,yddArticle);
        yddArticleMapper.insert(yddArticle);
        return Result.success();
    }

    /**
     * 取消操作
     *
     * @param type
     * @param articleId
     * @param action
     * @return
     */
    @Override
    public Result userDataHandle(String type, String articleId, String action) {
        if (type.equals("1")){
            if (action.equals("add")){
                YddUserData data = new YddUserData();
                data.setUserId(BaseContext.getCurrentId().intValue());
                data.setArticleId(Integer.valueOf(articleId));
                data.setType(Integer.valueOf(type));
                yddUserDataMapper.insert(data);
            }else {
                LambdaQueryWrapper<YddUserData> query = Wrappers.lambdaQuery();
                query.eq(YddUserData::getUserId,BaseContext.getCurrentId()).eq(YddUserData::getArticleId,articleId)
                        .eq(YddUserData::getType,type);
                yddUserDataMapper.delete(query);
            }
        }else {
            if (action.equals("add")){
                YddUserData data = new YddUserData();
                data.setUserId(BaseContext.getCurrentId().intValue());
                data.setArticleId(Integer.valueOf(articleId));
                data.setType(Integer.valueOf(type));
                yddUserDataMapper.insert(data);
            }else {
                LambdaQueryWrapper<YddUserData> query = Wrappers.lambdaQuery();
                query.eq(YddUserData::getUserId,BaseContext.getCurrentId()).eq(YddUserData::getArticleId,articleId)
                        .eq(YddUserData::getType,type);
                yddUserDataMapper.delete(query);
            }
        }
        return Result.success();
    }

    /**
     * 修改账户信息
     *
     * @param yddUser
     * @return
     */
    @Override
    public Result updateUser(YddUser yddUser) {
        removeById(yddUser.getId());
        YddUser user = new YddUser();
        BeanUtils.copyProperties(yddUser,user);
        save(user);

        return Result.success();
    }

    /**
     * 分类查询
     *
     * @param page
     * @param pageSize
     * @param cateid
     * @return
     */
    @Override
    public Result getlist(String page, String pageSize, String cateid) {
        UserDataVo vo = new UserDataVo();
        IPage<YddArticle> iPage=new Page<>(Integer.valueOf(page),Integer.valueOf(pageSize));
        LambdaQueryWrapper<YddArticle> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(YddArticle::getCateid,cateid);
        IPage<YddArticle> articleIPage = yddArticleMapper.selectPage(iPage, queryWrapper);
        DataPage pageResult = new DataPage();
        pageResult.setData(articleIPage.getRecords());
        pageResult.setCurrentPage(articleIPage.getCurrent());
        pageResult.setCount(articleIPage.getTotal());
        pageResult.setPageSize( articleIPage.getSize());
        pageResult.setTotalPages(articleIPage.getPages());
        vo.setList(pageResult);
        return Result.success(vo);
    }

    public List<YddAdvimg> getydd(String str){
        LambdaQueryWrapper<YddAdvimg> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(YddAdvimg::getAdvimgpos,"15");
        List<YddAdvimg> yddAdvimgs = yddAdvimgMapper.selectList(lambdaQuery);

        return yddAdvimgs;
    }
    public ChildrenVo chidr(String str){
        LambdaQueryWrapper<SysConfig> query = Wrappers.lambdaQuery();
        query.eq(SysConfig::getGroupValue,str);
        List<SysConfig> sysConfigs = sysConfigMapper.selectList(query);
        ChildrenVo childrenVo = new ChildrenVo();
        childrenVo.setData(sysConfigs);
        childrenVo.setName(str);
        return childrenVo;
    }





}
